﻿using System;
using System.Text.RegularExpressions;

namespace StockAccessors.Interdin.Model
{
	internal class DetailsPage
	{
		#region Attributes

		private readonly string _data;

		#endregion

		#region Properties

		public int ContractNumber { get; private set; }
		public int IP { get; private set; }
		public int Year { get; private set; }
		public int Month { get; private set; }
		public string St { get; private set; }
		public string RKNR { get; private set; }
		public string A { get; private set; }
		public string IO { get; private set; }
		public string DD { get; private set; }

		#endregion

		#region Public Methods

		public DetailsPage(string data)
		{
			_data = data;

			this.ParseData();
		}

		#endregion

		#region Private Methods

		private void ParseData()
		{
			// Drop the unneeded part
			int startIndex = _data.IndexOf(@"<form name='Operacion'", StringComparison.InvariantCultureIgnoreCase);
			int endIndex = _data.IndexOf(@"</form>", startIndex, StringComparison.InvariantCultureIgnoreCase) + @"</form>".Length;

			string subPage = _data.Substring(startIndex, endIndex - startIndex);

			foreach (Match inputItem in Regex.Matches(subPage, @"<input .*?>"))
			{
				string inputText = inputItem.ToString();
				if (inputText.IndexOf("name", StringComparison.InvariantCultureIgnoreCase) >= 0 && inputText.IndexOf("value", StringComparison.InvariantCultureIgnoreCase) >= 0)
				{
					startIndex = inputText.IndexOf("name='", StringComparison.InvariantCultureIgnoreCase) + "name='".Length;
					endIndex = inputText.IndexOf("'", startIndex, StringComparison.InvariantCultureIgnoreCase);
					string name = inputText.Substring(startIndex, endIndex - startIndex);

					startIndex = inputText.IndexOf("value='", StringComparison.InvariantCultureIgnoreCase) + "value='".Length;
					endIndex = inputText.IndexOf("'", startIndex, StringComparison.InvariantCultureIgnoreCase);
					string value = inputText.Substring(startIndex, endIndex - startIndex);

					this.SetAttribute(name, value);
				}
			}
		}

		private void SetAttribute(string name, string value)
		{
			switch (name)
			{
				case "nc":
					this.ContractNumber = Int32.Parse(value);
					break;
				case "IP":
					this.IP = Int32.Parse(value);
					break;
				case "YY":
					this.Year = Int32.Parse(value);
					break;
				case "M":
					this.Month = Int32.Parse(value);
					break;
				case "St":
					this.St = value;
					break;
				case "RKNR":
					this.RKNR = value;
					break;
				case "A":
					this.A = value;
					break;
				case "IO":
					this.IO = value;
					break;
				case "DD":
					this.DD = value;
					break;
			}
		}

		#endregion
	}
}
